這個得上一篇:https://ithelp.ithome.com.tw/articles/10258374
看到數量再多按幾次會增加.再到cart-status.component.ts檔案:
然後也是updateCartStatus按右鍵修正:
再修改內容:
import { CartService } from './../../services/cart.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-cart-status',
templateUrl: './cart-status.component.html',
styleUrls: ['./cart-status.component.css']
})
export class CartStatusComponent implements OnInit {
totalPrice: number = 0.00;
totalQuantity: number = 0;
constructor(private CartService: CartService) { }
ngOnInit(): void {
this.updateCartStatus();
}
updateCartStatus() {
this.CartService.totalPrice.subscribe(
data => this.totalPrice = data
);
this.CartService.totalQuantity.subscribe(
data => this.totalQuantity = data
);
}
}
然後再到cart-status.component.html檔案:修正{{ totalPrice | currency: 'USD'}}和 {{ totalQuantity}}
<div class="cart-area d-n">
<a href="shopping-detail.html">
<div class="total">{{ totalPrice | currency: 'USD'}}
<span> {{ totalQuantity}}</span>
</div>
<i class="fa fa-shopping-cart" aria-hidden="true"></i>
</a>
</div>
最原本空的
然後有新增的
再來到cart.service.ts檔案:
找到這段CODE
刪掉他再修正~tempCartItem => tempCartItem.id === tempCartItem.id持續測試到修正(3個等於)
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Equality_comparisons_and_sameness
嚴格相等(===)
嚴格相等比較兩個值,而被比較的兩個值都不會轉換成其他型別。如果值是不同型別,就會被視為不相等。如果兩值型別相同但不是數字,若值相同,則為相等。此外,如果兩個值皆為數字,只要他們是 NaN 以外的同一值,或者 +0 和 -0,則為相等。
import { CartItem } from './../common/cart-item';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartService {
CartItems: CartItem[]=[];
totalPrice: Subject<number> = new Subject<number>();
totalQuantity: Subject<number> = new Subject<number>();
constructor() { }
addToCart(theCartItem:CartItem){
let alreadyExistsInCart : boolean = false;
let existingCartItem: CartItem = undefined;
if (this.CartItems.length>0){
existingCartItem = this.CartItems.find( tempCartItem => tempCartItem.id === tempCartItem.id);
alreadyExistsInCart =(existingCartItem != undefined);
}
if (alreadyExistsInCart){
existingCartItem.quantity++;
}
else{
this.CartItems.push(theCartItem);
}
this.computeCartTotals();
}
computeCartTotals() {
let totalPriceValue: number =0;
let totalQuantityValue: number =0;
for(let currentCartItem of this.CartItems){
totalPriceValue += currentCartItem.quantity * currentCartItem.unitPrice;
totalQuantityValue += currentCartItem.quantity;
}
this.totalPrice.next(totalPriceValue);
this.totalQuantity.next(totalQuantityValue);
this.logCartData(totalPriceValue, totalQuantityValue);
}
logCartData(totalPriceValue: number, totalQuantityValue: number) {
console.log('Contents of the cart');
for (let tempCartItem of this.CartItems){
const subTotalPrice = tempCartItem.quantity * tempCartItem.unitPrice;
console.log(`name: ${tempCartItem.name}, quantity=${tempCartItem.quantity},unitPrice=${tempCartItem.unitPrice},subTotalPrice=${subTotalPrice}`);
}
console.log(`totalPrice: ${totalPriceValue.toFixed(2)}, totalQuantity: ${totalPriceValue}`);
console.log('----');
}
}
用chrome 開發者工具可以看到任點都OK
讓產品細目裡的加入購物車的按鍵也有作用
到product-details.component.html檔案-從這句修改開始
<div class="detail-section">
<div class="container-fluid">
<img src="{{product.imageUrl}}" class="detail-img">
<h3>{{product.name}}</h3>
<div class="price">{{product.unitPrice |currency:'USD'}}</div>
<button (click)="addToCart()" class="btn btn-primary btn-sm" >Add to cart</button>
<hr>
<h4>Description</h4>
<p>{{product.description}}</p>
<a routerLink="/products" class="mt-5">Back to Product List</a>
</div>
</div>
到這裡的addToCart會反紅
是因為要去product-details.component.ts 檔案新增:
再到最下面:
import { CartService } from './../../services/cart.service';
import { Routes, ActivatedRoute } from '@angular/router';
import { ProductService } from 'src/app/services/product.service';
import { Product } from 'src/app/common/product';
import { Component, OnInit } from '@angular/core';
import { CartItem } from 'src/app/common/cart-item';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {
product:Product = new Product();
constructor(private ProductService:ProductService,
private CartService: CartService,
private route:ActivatedRoute) { }
ngOnInit(): void {
this.route.paramMap.subscribe(() =>{
this.handleProductDetails();
})
}
handleProductDetails() {
const theProductId:number = +this.route.snapshot.paramMap.get('id');
this.ProductService.getProduct(theProductId).subscribe(
data =>{
this.product = data;
}
)
}
addToCart(){
console.log(`Adding to cart: ${this.product.name},${this.product.unitPrice}`);
const theCartItem = new CartItem(this.product);
this.CartService.addToCart(theCartItem);
}
}
用chrome的開發者工具來檢查
這個得下一篇:https://ithelp.ithome.com.tw/articles/10258452